﻿using System;
using System.ComponentModel;
using System.Windows.Input;
using ClientOverflow.Core;
using ClientOverflow.DataTransferObjects;
using ClientOverflow.ViewModels.Interfaces;

namespace ClientOverflow.ViewModels.Login
{
    /// <summary>
    /// LoginCommand is in charge routing calls on login to the WCF service that communicates with the database
    /// and verify the user exitance and the password. The command is bounded through the interface to the
    /// initiating view-model. When the view-model properties change the status of the command changes. This
    /// command can be executed only when both username & password are filled. The command performs as an
    /// ovserver of the view-model (ILoginViewModel interface) and changes its status according to the view-model
    /// state.
    /// </summary>
    internal class LoginCommand : ICommand
    {
        private readonly ILoginViewModel viewModel;

        public LoginCommand(ILoginViewModel viewModel)
        {
            this.viewModel = viewModel;
            this.viewModel.PropertyChanged += OnViewModelChanged;
        }

        private void OnViewModelChanged(object sender, PropertyChangedEventArgs e)
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }

        public void Execute(object parameter)
        {
            User user;
            using (var serviceClient = ServicesFactory.CreateClientOverflowServiceClient())
            {
                user = serviceClient.GetUser(viewModel.Email, viewModel.Password);
            }

            if (user == null)
            {
                viewModel.LoginFailed();
                return;
            }

            ServicesProviderFactory.GetInstance().LoginService.Login(user);
        }

        public bool CanExecute(object parameter)
        {
            return !string.IsNullOrEmpty(viewModel.Email) && !string.IsNullOrEmpty(viewModel.Password);
        }

        public event EventHandler CanExecuteChanged=(sender, args) => { };
    }
}